﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.ExceptionHandling;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using User.Api.Common;
using Newtonsoft.Json.Serialization;

namespace User.Api
{
    public static class WebApiConfig
    {
        //public static void Register(HttpConfiguration config)
        //{
        //    // Web API 配置和服务

        //    // Web API 路由
        //    config.MapHttpAttributeRoutes();

        //    config.Routes.MapHttpRoute(
        //        name: "DefaultApi",
        //        routeTemplate: "{controller}/{action}/{id}",
        //        defaults: new { id = RouteParameter.Optional }
        //    );
        //}

        public static void Register(HttpConfiguration config)
        {
            // Web API 路由
            config.MapHttpAttributeRoutes();
            // There can be multiple exception loggers. (By default, no exception loggers are registered.)
            config.Services.Add(typeof(IExceptionLogger), new GlobalExceptionLogger());

            // There must be exactly one exception handler. (There is a default one that may be replaced.)
            // To make this sample easier to run in a browser, replace the default exception handler with one that sends
            // back text/plain content for all errors.
            config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            //忽略实体类Serializable标记,经测试有DataContract类时，不加DataMember特性时，依然不起作用
            var settings = new JsonSerializerSettings()
            {
                ContractResolver = new DefaultContractResolver()
                {
                    IgnoreSerializableAttribute = true
                }
            };
            ////返回时间类型数据不带T
            //settings.Converters.Add(
            //    new IsoDateTimeConverter()
            //    {
            //        DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
            //    }
            //    );
            settings.Converters.Add(new JSONDateTimeJsonConverter());
            config.Formatters.JsonFormatter.SerializerSettings = settings;

            //控制返回xml和json格式,如查看json格式数据可用类似网址 http://192.168.1.209:8095/UserApi/User/GetUserInfo?userID=5&t=json
            config.Formatters.JsonFormatter.MediaTypeMappings.Add(new QueryStringMapping("t", "json", "application/json"));
            config.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("t", "xml", "application/xml"));

        }

        /// <summary>
        /// 时间类型格式转化
        /// </summary>
        public class JSONDateTimeJsonConverter : DateTimeConverterBase
        {
            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {
                if (reader.Value == null)
                    return DateTime.MinValue;

                return (DateTime)reader.Value;
            }

            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                DateTime date = (DateTime)value;
                if (date != DateTime.MinValue)
                {
                    writer.WriteValue(date.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture));
                }
                else
                {
                    writer.WriteRawValue("null");
                }
            }
        }
    }

   

}
